package com.xiejun.netty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class EnhancedSimpleNettyServer {
    
    private final int port;
    private final ChannelHandler handler;
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    
    public EnhancedSimpleNettyServer(int port, ChannelHandler handler) {
        this.port = port;
        this.handler = handler;
    }
    
    public void start() throws IOException {
        // 打开选择器
        selector = Selector.open();
        
        // 打开服务器套接字通道
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(port));
        
        // 注册接受连接事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        System.out.println("Enhanced Simple Netty Server started on port " + port);
        
        // 事件循环
        while (true) {
            // 等待事件
            selector.select();
            
            // 处理事件
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                
                if (key.isAcceptable()) {
                    handleAccept(key);
                } else if (key.isReadable()) {
                    handleRead(key);
                }
                
                keyIterator.remove();
            }
        }
    }
    
    private void handleAccept(SelectionKey key) throws IOException {
        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        SocketChannel clientChannel = serverChannel.accept();
        clientChannel.configureBlocking(false);
        
        // 调用处理器的连接事件方法
        handler.channelConnected(clientChannel);
        
        // 注册读事件
        clientChannel.register(selector, SelectionKey.OP_READ);
    }
    
    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel clientChannel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        
        int bytesRead = clientChannel.read(buffer);
        if (bytesRead == -1) {
            // 客户端关闭连接
            handler.channelDisconnected(clientChannel);
            clientChannel.close();
            return;
        }
        
        // 处理读取到的数据
        buffer.flip();
        
        // 调用处理器的读事件方法
        handler.channelRead(clientChannel, buffer);
    }
    
    public static void main(String[] args) {
        try {
            ChannelHandler handler = new EchoServerHandler();
            new EnhancedSimpleNettyServer(8081, handler).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}